<?php
require_once ROOT . DS . 'app' . DS . 'controllers' . DS . 'components' . DS . 'policy_validate_machine' . DS . 'PolicyValidateMachine.php';
/**
 * Class of PolicyMachine
 *
 * @author BUI TIEN HIEP
 * @email bthiep@lhv.vn
 */
class PolicyMachineComponent extends Object {

    private $reportValidateMessages = array(); //Store messages

    /**
     * Validate a report
     * @param type $expenses
     * @param type $policies
     * @return boolean
     */

    public function validateReport($expenses, $policies) {
        $bRet = false;
        $validateMachine = new PolicyValidateMachine();
        if ($validateMachine->validate($policies, $expenses)) {
            $bRet = true;
            $this->reportValidateMessages = $validateMachine->getMessages();
        }
        return $bRet;
    }

    /**
     * Return report validate messages
     * @return type
     */
    public function getReportvalidateMessages() {
        return $this->reportValidateMessages;
    }

    /**
     * Create a policy
     * @param type $policy
     */
    public function createNewPolicy($policy) {
        $owerId = $policy['ower_id'];
        $owerType = $policy['owner_type'];
        $policyType = $policy['policy_type'];
        $template = $policy['template'];
        $name = $policy['name'];
        $description = $policy['$policy'];

        $policyQuery = "INSERT INTO policies
                        (
                        `owner_id`,
                        `owner_type`,
                        `policy_type`,
                        `template`,
                        `name`,
                        `description`,
                        `active`,
                        `created`
                        )
                        VALUES
                        (
                         $owerId,
                        '$owerType',
                        '$policyType',
                        '$template',
                        '$name',
                        '$description',
                        'Yes'
                        ,NOW()
                        );";
        $policyQuery.="SET @policy_id := LAST_INSERT_ID();";
        $fields = "`field`,`operator`,`value`,`operands`,`message`,`rule`,`policy_id`";
        $rules = $policy['rules'];
        $values = '';
        foreach ($rules as $rule) {
            $field = $rule['field'];
            $operator = $rule['operator'];
            $value = $rule['value'];
            $operands = $rule['operands'];
            $message = $rule['message'];
            $rule = $rule['rule'];
            $policyId = $rule['policy_id'];
            $values.="('$field','$operator','$value','$operands','$message','$rule',@policy_id),";
        }
        $values = rtrim($values, ",");
        $policyQuery.="INSERT INTO policies_rules($fields) VALUES $values ;";
        $this->Query($policyQuery);
        return true;
    }

    /**
     * Update a policy
     * @param type $policy
     */
    public function updatePolicy($policy) {
        $policyId = $policy['id'];
        $ownerId = $policy['owner_type'];
        $ownerType = $policy['owner_type'];
        $policyType = $policy['policy_type'];
        $template = $policy['template'];
        $name = $policy['name'];
        $description = $policy['$policy'];
        $policyQuery = "IF EXISTS( SELECT `id` FROM policies WHERE `id` = $policyId ) THEN
                        BEGIN
                            UPDATE policies
                            SET 
                                    `owner_id` = $ownerId,
                                    `owner_type` = '$ownerType',
                                    `policy_type` = '$policyType',
                                    `template` = '$template',
                                    `name` = '$name',
                                    `description` = '$description',
                                    `updated` = NOW()
                            WHERE `id` = $policyId;
                            DELETE FROM policies_rule
                            WHERE `policy_id` = $policyId;";
        $fields = "`field`,`operator`,`value`,`operands`,`message`,`rule`,`policy_id`";
        $rules = $policy['rules'];
        $values = '';
        foreach ($rules as $rule) {
            $field = $rule['field'];
            $operator = $rule['operator'];
            $value = $rule['value'];
            $operands = $rule['operands'];
            $message = $rule['message'];
            $rule = $rule['rule'];
            $policyId = $rule['policy_id'];
            $values.="('$field','$operator','$value','$operands','$message','$rule',$policyId),";
        }
        $values = rtrim($values, ",");
        $policyQuery.="INSERT INTO policies_rules($fields) VALUES $values ;";
        $policyQuery.="END;";
        $policyQuery.="END IF;";
        $this->Query($policyQuery);
        return true;
    }

    /**
     * Get Policies by Owner Id
     * @param type $owerId
     */
    public function getPolicies($owerId) {
        $res = $this->Query("call stp_GetPolicies $owerId");
        if (empty($res))
            return null;
        for ($i = 0; $i < count($res); $i++) {
            $res[i]['rules'] = json_decode($res[i]['rules'], true);
        }
        return $res;
    }

}
